package com.tangyuan.video.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangyuan.common.result.Result;
import com.tangyuan.dto.GivingGiftDto;
import com.tangyuan.feignapis.user.IUserBalanceFeignClient;
import com.tangyuan.model.UserBalance;
import com.tangyuan.model.Video;
import com.tangyuan.model.VideoGift;
import com.tangyuan.model.VideoGiftRecord;
import com.tangyuan.result.oConvertUtils;
import com.tangyuan.video.mapper.VideoGiftMapper;
import com.tangyuan.video.service.IVideoGiftRecordService;
import com.tangyuan.video.service.IVideoGiftService;
import com.tangyuan.video.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description: video_gift
 * @Author: jeecg-boot
 * @Date: 2024-03-12
 * @Version: V1.0
 */
@Service
public class VideoGiftServiceImpl extends ServiceImpl<VideoGiftMapper, VideoGift> implements IVideoGiftService {

    // @Autowired
    // private IUserBalanceService userBalanceService;

    @Autowired
    private IVideoGiftRecordService videoGiftRecordService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private IUserBalanceFeignClient userBalanceServiceClient;

    /**
     * 用户赠送礼物
     *
     * @param givingGiftDto
     * @return
     */
    @Transactional
    @Override
    public Result givingGift(GivingGiftDto givingGiftDto,Long userId) {

        UserBalance balance = userBalanceServiceClient.getUserBalance(userId);
        if (givingGiftDto.getGiftCount() == null) {
            givingGiftDto.setGiftCount(1);
        }
        Video video = videoService.getById(givingGiftDto.getVideoId());
        VideoGift gift = this.getById(givingGiftDto.getGiftId());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        long count = videoGiftRecordService.count(new LambdaQueryWrapper<VideoGiftRecord>().like(VideoGiftRecord::getCreateTime, format.format(new Date())).eq(VideoGiftRecord::getUserId, userId).eq(VideoGiftRecord::getGiftId, gift.getId()));
        if (gift.getGiftMoney().compareTo(new BigDecimal(0)) == 0) {
            if (gift.getGiftLimit() != -1) {
                if (count >= gift.getGiftLimit()) {
                    return Result.fail("赠送数量超过限制！");
                }
            }
            // 添加打赏记录
            VideoGiftRecord videoGiftRecord = new VideoGiftRecord();
            videoGiftRecord.setUserId(userId);
            videoGiftRecord.setGetUserId(video.getUserId());
            videoGiftRecord.setGiftId(gift.getId());
            videoGiftRecord.setGiftImage(gift.getGiftImage());
            videoGiftRecord.setGiftName(gift.getGiftName());
            videoGiftRecord.setGiftMoney(new BigDecimal("0"));
            videoGiftRecord.setGiftCount(givingGiftDto.getGiftCount());
            videoGiftRecord.setGitCountMoney(new BigDecimal("0"));
            videoGiftRecord.setCreateTime(new Date());
            videoGiftRecordService.save(videoGiftRecord);
            return Result.ok("操作成功！");
        }
        if (balance != null && video != null) {
            if (gift.getGiftLimit() != -1) {
                if (count >= gift.getGiftLimit()) {
                    return Result.fail("赠送数量超过限制！");
                }
            }
            BigDecimal money = gift.getGiftMoney();
            if (gift.getGiftPreferential() == 1) {
                money = gift.getGiftPreferentialMoney();
            }
            BigDecimal giftMoney = money.multiply(new BigDecimal(givingGiftDto.getGiftCount()));
            if (balance.getBalance().compareTo(giftMoney) > 0) {
                // 添加余额记录
                UserBalance userBalance = new UserBalance();
                userBalance.setUserId(userId);
                userBalance.setType(2);
                userBalance.setTransactionId("DS" + oConvertUtils.orderNo());
                userBalance.setOrderNo("DS" + oConvertUtils.orderNo());
                userBalance.setUpBalance(giftMoney);
                userBalance.setBalance(balance.getBalance().subtract(giftMoney));
                userBalance.setCreateTime(new Date());
                userBalanceServiceClient.saveUserBalance(userBalance);
                // 添加打赏记录
                VideoGiftRecord videoGiftRecord = new VideoGiftRecord();
                videoGiftRecord.setUserId(userId);
                videoGiftRecord.setGetUserId(video.getUserId());
                videoGiftRecord.setGiftId(gift.getId());
                videoGiftRecord.setGiftImage(gift.getGiftImage());
                videoGiftRecord.setGiftName(gift.getGiftName());
                videoGiftRecord.setGiftMoney(money);
                videoGiftRecord.setGiftCount(givingGiftDto.getGiftCount());
                videoGiftRecord.setGitCountMoney(giftMoney);
                videoGiftRecord.setCreateTime(new Date());
                videoGiftRecordService.save(videoGiftRecord);
                return Result.ok("操作成功！");
            }
        }
        return Result.errorMoney("操作失败，余额不足，请充值！");
    }

    @Override
    public Result getGiftList(Long userId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        LambdaQueryWrapper<VideoGift> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VideoGift::getIsDelete, 0);
        List<VideoGift> list = this.list(queryWrapper);
        list.forEach(item -> {
            if (item.getGiftLimit() != -1) {
                long count = videoGiftRecordService.count(new LambdaQueryWrapper<VideoGiftRecord>().like(VideoGiftRecord::getCreateTime, format.format(new Date()))
                        .eq(VideoGiftRecord::getUserId, userId).eq(VideoGiftRecord::getGiftId, item.getId()));
                long num = item.getGiftLimit() - count;
                item.setFreeNum(num);
                if (num < 0) {
                    item.setFreeNum(0L);
                }
            }else {
                item.setFreeNum(-1l);
            }
        });
        return Result.ok(list);
    }


}
